package com.qk.management.web.interceptor;

import com.qk.utils.CurrentUserContextHolders;
import com.qk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

/**
 *
 * @author lyl
 * @created 2025/10/11 15:42
 * @description
 *
 */
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,@NonNull Object handler){
        String token = request.getHeader("token");
        if (Objects.isNull(token)){
            log.info("token为不存在");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        try {
            Claims claims = JwtUtils.parseToken(token);
            log.info("用户已登录,用户id为:{}",claims.get("id"));
            log.info("用户已登录,用户名为:{}",claims.get("username"));
            Integer id = claims.get("id",Integer.class);
            CurrentUserContextHolders.set(id);
            return true;
        } catch (Exception e) {
            log.info("token解析失败");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
    }
    @Override
    public void afterCompletion(@NonNull HttpServletRequest request,@NonNull HttpServletResponse response,@NonNull Object handler, Exception ex) {
        CurrentUserContextHolders.remove();
    }
}
